package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.INavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements INavService {
    @Override
    public List<NavModel> getNavModelListForHome() {
//        final List<NavModel>[] list = new List[]{new ArrayList<>()};
//        for (int i = 0; i < 500; i++) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    System.out.println(Thread.currentThread().getName());
//                    list[0] = getData();
//                }
//            }, "thread" + i).start();
//        }
//        return list[0];
        NavDao navDao = new NavImpl();
        return navDao.getNavModelListForHome();
    }

    private synchronized List<NavModel> getData() {

        Jedis jedis = new Jedis();
        jedis.select(8);
        List<NavModel> list = new ArrayList<>();
        if (jedis.exists("navHref")) {
            long length = jedis.llen("navHref");//取得list长度
//            取得key值
            List<String> navHrefList = jedis.lrange("navHref", 0, -1);
            List<String> navTitleList = jedis.lrange("navTitle", 0, -1);
            for (int i = 0; i < length; i++) {
                NavModel navModel = new NavModel();
                navModel.setHref(navHrefList.get(i));
                navModel.setTitle(navTitleList.get(i));
                list.add(navModel);
            }
            System.out.println("nav---redis");
        } else {
            NavDao navDao = new NavImpl();
            list = navDao.getNavModelListForHome();
            for (NavModel model : list
            ) {
                jedis.rpush("navHref", model.getHref());
                jedis.rpush("navTitle", model.getTitle());
            }
            System.out.println("nav---mysql");

        }
        return list;
    }

    public int update(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int result = navDao.update(navModel);
        if (result > 0) {
            Jedis jedis = new Jedis();
            jedis.del("navHref", "navTitle");
        }
        return result;
    }
}
